#import "ParticleFountain.h"

@implementation ParticleFountain

- (id) init
{
	[super init];
	
	return self;
}

- (void) initLazy
{
	[super initLazy];
	
	time.current[0] = 0;
	time.min[0] = 0;
	time.max[0] = 10000;
	time.delta[0] = 0.01;

	/* Setup GLSL */
	{
		NSBundle *bundle;
		NSString *vertex_string, *fragment_string;

		bundle = [NSBundle bundleForClass: [self class]];

		/* Load vertex and fragment shader */
		vertex_string   = [bundle pathForResource: @"ParticleFountain" ofType: @"vert"];
		vertex_string   = [NSString stringWithContentsOfFile: vertex_string];
		fragment_string = [bundle pathForResource: @"ParticleFountain" ofType: @"frag"];
		fragment_string = [NSString stringWithContentsOfFile: fragment_string];
		if ([self loadVertexShader: vertex_string fragmentShader: fragment_string])
			NSLog(@"Failed to load ParticleFountain");
			
		/* Setup uniforms */
		glUseProgramObjectARB(program_object);
		glUniform1fvARB(glGetUniformLocationARB(program_object, "time"), 1, PARAMETER_CURRENT(time));
	}

	/* make particles */
	{
		int i;
		particleCount = 1000;
		particles = malloc(4 * particleCount * sizeof(GLfloat));
		for (i = 0; i < particleCount; i++)
		{
			particles[i*4 + 0] = (float)rand() / (float)RAND_MAX;
			particles[i*4 + 1] = (float)rand() / (float)RAND_MAX;
			particles[i*4 + 2] = (float)rand() / (float)RAND_MAX;
			particles[i*4 + 3] = (float)rand() / (float)RAND_MAX;
		}
	}
}

- (void) dealloc
{
	[super dealloc];
}

- (NSString *) name
{
	return @"ParticleFountain";
}

- (NSString *) descriptionFilename
{
	NSBundle *bundle;
	NSString *string;
	bundle = [NSBundle bundleForClass: [self class]];
   string = [bundle pathForResource: @"ParticleFountain" ofType: @"rtf"];
	
	return string;
}

- (void) renderFrame
{
	[super renderFrame];
	
	glUseProgramObjectARB(program_object);
	
	PARAMETER_ANIMATE(time);
	glUniform1fvARB(glGetUniformLocationARB(program_object, "time"), 1, PARAMETER_CURRENT(time));

	glTranslatef(0.0f, 0.4f, 0.0f);

	glPushAttrib(GL_POINT_BIT);
	glPointSize(2.0);

	/* draw particles */
	{
		int i;
		glBegin(GL_POINTS);
		for (i = 0; i < particleCount; i++)
		{
			glColor4fv(&particles[i*4]);
			glVertex3fv(&particles[i*4]);
		}
		glEnd();
	}

	glPopAttrib();

	glUseProgramObjectARB(NULL);
}

@end
